import json
from flask import jsonify, redirect, url_for, request
# from flask import request as flask_resq
from datetime import date
from json import loads
import os

# from requests.api import request

from app import app
from app.spider import spider_api
from app.translateSpider import letter_api

def make_res(msg:str="ok", status:int=1, data=None):
    return {
        "msg": msg,
        "status": status,
        "data": data
    }

@app.route("/api/getNews")
def index():
    today = str(date.today())
    try:
        path = os.path.join("articalData", today + "News.json")
        print(path)
        with open(path) as f:
            data = loads(f.read())
        return jsonify(data)
    except IOError as e:
        print(e)
        spider_api()
        return redirect(url_for("index"))
    except Exception:
        pass
    return jsonify(data)


@app.route("/api/letter", methods=["GET", "POST"])
def translate_letter():
    print(request.json)
    letter = request.json.get("letter")
    # letter = loads(str(letter))
    if letter is None:
        return make_res(msg="error", status=-1, data="No letter")
    if letter == "":
        return jsonify(make_res(data=""))
    letter = letter_api(letter)
    return jsonify(make_res(data=letter))

@app.route("/api/refresh")
def refresh():
    spider_api()
    return "refresh success"

